package com.zzw.springboot.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzw.springboot.entity.Comment;
import com.zzw.springboot.entity.User;
import com.zzw.springboot.mapper.CommentMapper;
import com.zzw.springboot.service.ICommentService;
import com.zzw.springboot.service.IUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zzw
 * @since 2022-06-12 16:42:47
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {

    @Resource
    private IUserService userService;

    @Override
    public List<Comment> findCommentDetail(Integer articleId) {
        //查询所有
        List<Comment> articleComments = list(Wrappers.<Comment>lambdaQuery()
                .eq(Comment::getArticleId, articleId).orderByDesc(Comment::getTime));
        //查询用户信息（昵称、头像）
        articleComments = articleComments.stream().peek(comment -> {
            User user = userService.getOne(Wrappers.<User>lambdaQuery()
                    .select(User::getNickname, User::getAvatarUrl)
                    .eq(User::getId, comment.getUserId()));
            comment.setNickname(user.getNickname());
            comment.setAvatarUrl(user.getAvatarUrl());
        }).collect(Collectors.toList());

        //查询一级评论
        List<Comment> originList = articleComments.stream()
                .filter(comment -> Objects.isNull(comment.getOriginId()))
                .collect(Collectors.toList());

        //查询回复评论并设置到Children
        for (Comment origin : originList) {
            //回复对象集合
            List<Comment> comments = articleComments.stream()
                    .filter(comment -> origin.getId().equals(comment.getOriginId()))
                    .collect(Collectors.toList());
            //找到当前评论的父级
            List<Comment> finalArticleComments = articleComments;
            comments.forEach(comment -> {
                Optional<Comment> pComment = finalArticleComments.stream()
                        .filter(c1 -> c1.getId().equals(comment.getPid())).findFirst();
                pComment.ifPresent((v -> {
                    comment.setPUserId(v.getUserId());
                    comment.setPNickName(v.getNickname());
                }));
            });
            origin.setChildren(comments);
        }
        //设置评论子节点，回复内容
        return originList;
    }
}
